// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  if (event.word_id == null || event.word_id == 0) {
    return {
      _log: "error",
    }
  }

  //通过JS的方法获取当前年月日
  var date = new Date();
  date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  //获取年份  
  const Y = date.getFullYear();
  //获取月份  
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  //获取当日日期 
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

  let today = await db.collection('location').where({
    user_id: wxContext.OPENID,
    time: {
      year: Y,
      month: M,
      day: D,
    }
  }).get();
  if (today.data[0] == null) { //没有今天 直接添加

    await db.collection('location').add({
      data: {
        user_id: wxContext.OPENID,
        word_id: event.word_id,
        time: {
          year: Y,
          month: M,
          day: D
        }
      }
    })
    return {
      _log: "add",
    }
  } else { //有今天，update

    await db.collection('location').doc(today.data[0]._id).update({
      data: {
        word_id: event.word_id,
      }
    })
    return {
      _log: "update",
    }
  }

}